package com.losdun.aftersales.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.losdun.aftersales.domain.ContractOrder;
import com.losdun.aftersales.domain.Install;
import com.losdun.aftersales.enums.AftersalesTypeEnum;
import com.losdun.aftersales.enums.OrderStatusEnum;
import com.losdun.aftersales.enums.WorkStatusEnum;
import com.losdun.aftersales.manager.NoticeManager;
import com.losdun.aftersales.manager.NumberGenerator;
import com.losdun.aftersales.mapper.InstallMapper;
import com.losdun.aftersales.service.IContractOrderService;
import com.losdun.aftersales.service.IInstallService;
import com.losdun.common.constant.HttpStatus;
import com.losdun.common.exception.ServiceException;
import com.losdun.common.utils.DateUtils;
import com.losdun.common.utils.uuid.CodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * 售后安装Service业务层处理
 * 
 * @author swordye
 * @date 2025-08-19
 */
@Service
@Slf4j
public class InstallServiceImpl extends ServiceImpl<InstallMapper,Install> implements IInstallService
{
    @Autowired
    private InstallMapper installMapper;

    @Autowired
    private IContractOrderService contractOrderService;

    @Autowired
    private NumberGenerator numberGenerator;

    @Autowired
    private NoticeManager noticeManager;

    /**
     * 查询售后安装
     * 
     * @param id 售后安装主键
     * @return 售后安装
     */
    @Override
    public Install selectInstallById(Long id)
    {
        return installMapper.selectInstallById(id);
    }

    /**
     * 查询售后安装列表
     * 
     * @param install 售后安装
     * @return 售后安装
     */
    @Override
    public List<Install> selectInstallList(Install install)
    {
        return installMapper.selectInstallList(install);
    }

    /**
     * 新增售后安装
     * 
     * @param install 售后安装
     * @return 结果
     */
    @Override
    public int insertInstall(Install install)
    {
        install.setCreateTime(DateUtils.getNowDate());
        return installMapper.insertInstall(install);
    }

    /**
     * 修改售后安装
     * 
     * @param install 售后安装
     * @return 结果
     */
    @Override
    public int updateInstall(Install install)
    {
        install.setUpdateTime(DateUtils.getNowDate());
        return installMapper.updateInstall(install);
    }

    /**
     *
     * 检查更换师傅
     * @param install
     */
    public boolean checkChangeWorker(Install install) {
        if(install.getWorkerId()==null){
            return false;
        }
        Install old = installMapper.selectById(install.getId());
        return !install.getWorkerId().equals(old.getWorkerId());
    }


    /**
     * 批量删除售后安装
     * 
     * @param ids 需要删除的售后安装主键
     * @return 结果
     */
    @Override
    public int deleteInstallByIds(Long[] ids)
    {
        return installMapper.deleteInstallByIds(ids);
    }

    /**
     * 删除售后安装信息
     * 
     * @param id 售后安装主键
     * @return 结果
     */
    @Override
    public int deleteInstallById(Long id)
    {
        return installMapper.deleteInstallById(id);
    }

    @Override
    public void appInstallSave(Install install) {
        ContractOrder order = contractOrderService.selectContractOrderById(install.getOrderId());
        if(order== null){
            throw new ServiceException("原始订单不存在！", HttpStatus.SERVICE_EXCEPTION);
        }
        if(order.getSecondTimes()!=1){
            if(checkInstallExists(order.getId(),install.getType())){
                throw new ServiceException("您已预约服务过一次，二次服务需另外收费，请拨打客服电话400-699-4988进行预约！",HttpStatus.SERVICE_EXCEPTION);
            }
        }
        if(checkInstallTimeCount(install.getInstallTime())>10){
            throw new ServiceException("当天预约已满，请选择其他日期！",HttpStatus.SERVICE_EXCEPTION);
        }
        if(DateUtils.differentDaysByMillisecond(new Date(),install.getInstallTime()) <3){
            throw new ServiceException("预约时间至少要3天后！",HttpStatus.SERVICE_EXCEPTION);
        }

        //TODO 预约安装判断是否收到货
        if(install.getType().equals(AftersalesTypeEnum.INSTALL.getValue())){

            if(!OrderStatusEnum.RECEIVED.getValue().equals(order.getStatus())){
                throw new ServiceException("您未确认收货无法预约安装，请先到订单中心确认收货！",HttpStatus.SERVICE_EXCEPTION);
            }

        }
        install.setProductModel(order.getProductModel());
        install.setWorkNo(numberGenerator.generateNo("IWO"));
        install.setFinishCode(CodeUtils.generateNumberCode(4));
        this.insertInstall(install);
        //发送预约成功通知
        noticeManager.bookInstallSuccessSendNotice(order,install);
    }

    @Override
    public void completedInstall(Long id, String finishCode) {
        Install install=this.getById(id);
        if(install==null){
            throw new RuntimeException("安装工单不存在！");
        }
        if(!install.getFinishCode().equals(finishCode)){
            throw new RuntimeException("验证码错误！");
        }
        install.setStatus(WorkStatusEnum.COMPLETED.getValue());
        install.setFinishTime(DateUtils.getNowDate());
        this.updateById(install);
        //如果是安装订单完成修改订单状态
        if(install.getType().equals(AftersalesTypeEnum.INSTALL.getValue())){
            contractOrderService.updateStatus(install.getOrderId(),OrderStatusEnum.COMPLETED.getValue(),LocalDate.now());
        }
        //发送安装完成通知
        noticeManager.installCompletedSendNotice(install);
    }

    @Override
    public List<Install> queryUnCompletedInstall() {
        LambdaQueryWrapper<Install> qw=new LambdaQueryWrapper<>();
        qw.ne(Install::getStatus,WorkStatusEnum.COMPLETED.getValue());
        return baseMapper.selectList(qw);
    }

    @Override
    public List<Install> queryOrderInstall(Long orderId) {
        LambdaQueryWrapper<Install> qw=new LambdaQueryWrapper<>();
        qw.eq(Install::getOrderId,orderId);
        return baseMapper.selectList(qw);
    }

    private boolean checkInstallExists(Long orderId,Integer type){
        LambdaQueryWrapper<Install> qw=new LambdaQueryWrapper<>();
        qw.eq(Install::getOrderId,orderId).eq(Install::getType,type);
        return baseMapper.selectCount(qw)>0;
    }


    private Long checkInstallTimeCount(Date time){
        LambdaQueryWrapper<Install> qw=new LambdaQueryWrapper<>();
        qw.between(Install::getInstallTime,DateUtils.getStartOfDay( time),DateUtils.getEndOfDay(time));
        return baseMapper.selectCount(qw);

    }
}
